<script lang="ts">
	import Checkbox from './Checkbox.svelte';
	import type { Variant } from './types';

	// 内部类型声明
	interface Option {
		value: any;
		label: string;
	}

	interface Props {
		label?: string;
		options: Option[]; // 接收完整选项对象数组
		modelValue: any[];
		variant?: Variant;
		size?: 'sm' | 'md' | 'lg' | null;
		disabled?: boolean;
		onchange?: (value: any[]) => void;
	}

	// 属性定义
	export let label: Props['label'] = '全选';
	export let options: Props['options'] = [];
	export let modelValue: Props['modelValue'] = [];
	export let variant: Props['variant'] = 'primary';
	export let size: Props['size'] = null;
	export let disabled: Props['disabled'] = false;
	export let onchange: Props['onchange'] = undefined;

	const selectAllValue = Symbol('select-all');
	let currentValue: any[] = [];
	let currentIndeterminate: boolean = false;

	// 同步全选状态与子选项状态
	$: {
		const totalCount = options.length;
		const selectedCount = modelValue.filter((val) =>
			options.some((option) => option.value === val)
		).length;

		// 全选状态：所有选项都被选中
		currentValue = totalCount > 0 && selectedCount === totalCount ? [selectAllValue] : [];
		// 半选状态：部分选项被选中
		currentIndeterminate = totalCount > 0 && selectedCount > 0 && selectedCount < totalCount;
	}

	// 全选/取消全选的逻辑处理
	function handleSelectAllChange(values: any[] | boolean) {
		const isChecked = Array.isArray(values) ? values.includes(selectAllValue) : false;
		// 全选时设置所有选项value，取消全选时清空
		const newModelValue = isChecked ? options.map((option) => option.value) : [];
		modelValue = newModelValue;
		// 触发回调
		onchange?.(newModelValue);
	}
</script>

<Checkbox
	{label}
	bind:modelValue={currentValue}
	value={selectAllValue}
	indeterminate={currentIndeterminate}
	{variant}
	{size}
	{disabled}
	onchange={handleSelectAllChange}
/>
